import { useState, useEffect } from 'react'
import { Flex, FloatingBall } from 'react-vant'
import { BackTop } from '@react-vant/icons'
import './style.less'

const BackToTop = () => {
  const [showButton, setShowButton] = useState(false)

  useEffect(() => {
    window.addEventListener('scroll', handleScroll)
    return () => {
      window.removeEventListener('scroll', handleScroll)
    }
  }, [])

  const handleScroll = () => {
    if (window.pageYOffset > 300) {
      setShowButton(true)
    } else {
      setShowButton(false)
    }
  }

  const handleClick = () => {
    window.scrollTo({
      top: 0,
      behavior: 'smooth'
    })
  }

  return (
    <FloatingBall
      className='demo-floating-box-bubble'
      offset={{
        right: 20,
        bottom: 70
      }}
      style={{
        '--rv-floating-box-size': '60px'
      }}
      adsorb={{
        // 滚动缩进比例
        indent: 0.5,
        // 近边停靠距离
        distance: 20
      }}
    >
      {showButton && (
        <Flex
          align='center'
          justify='center'
          className='main-button'
          onClick={() => handleClick()}
        >
          <BackTop />
        </Flex>
      )}
    </FloatingBall>
  )
}

export default BackToTop
